package com.yw.swagger.tool.Aop;

import com.yw.swagger.model.AppAuthor;
import com.yw.swagger.service.AuthorService;
import com.yw.swagger.tool.AjaxResult;
import com.yw.swagger.tool.Convert;
import com.yw.swagger.tool.Global;
import com.yw.swagger.tool.Utils.ServletUtils;
import com.yw.swagger.tool.Utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: Abeiv
 * @Description:
 * @Date: 2019/10/25 15:22
 */
@Aspect
@Component
public class Log extends ServletUtils {
    private Logger logger = LoggerFactory.getLogger(Log.class);

    @Autowired
    private AuthorService authorService;

    @Pointcut("execution(* com.yw.swagger.controller.*.*(..))")
    public void webLog() {
    }

    @Around("webLog()")
    public Object aroundMethod(ProceedingJoinPoint pjd) throws Throwable {
        Object result = null;
        String methodName = pjd.getSignature().getName();
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String sign = getParameter("author");
        logger.debug("author:{}",sign);
        try {
            // 记录下请求内容
            logger.info("HTTP_METHOD : " + request.getMethod());
            logger.info("IP : " + request.getRemoteAddr());
            logger.info("URL : " + request.getRequestURL().toString());
            logger.info("CLASS_METHOD : " + pjd.getSignature().getDeclaringTypeName() + "." + methodName);
            logger.info("ARGS : " + Arrays.toString(pjd.getArgs()));
            Boolean t = false;

            if(!vftMethod(methodName)){
                if(StringUtils.isNull(sign) || sign.length() != 10){
                    return AjaxResult.error("非法请求");
                }
                List<AppAuthor> l = null;

                if(getSession().getAttribute("sign")==null){
                    l = authorService.selectAuthorList();
                    getSession().setMaxInactiveInterval(60*60*24);
                    getSession().setAttribute("sign",l);
                    t = true;
                }else{
                    l = (List<AppAuthor>) getSession().getAttribute("sign");
                }

                if (!authorService.forList(l,sign)) {
                    if(t){
                        return AjaxResult.error("非法请求");
                    }
                    l = authorService.selectAuthorList();
                    if(!authorService.forList(l,sign)){
                        return AjaxResult.error("非法请求");
                    }
                }
            }
            // 执行方法
            result = pjd.proceed();

            logger.info("method={},ends with={}", methodName, result);
        } catch (Throwable e) {

            logger.error("The method={}，occurs exception:={}", methodName, e);
            throw new RuntimeException(e);

        }




        return result;
    }

    /**
     * 验证请求是否拦截
     * @param mothod
     * @return
     */
    public static Boolean vftMethod (String mothod){
        String[] interceptor = Convert.toStrArray(Global.getConfig("yw.interceptor"));
        for (int i = 0; i < interceptor.length; i++){
            if(interceptor[i].equals(mothod)){
                return true;
            }
        }
        return false;
    }
}
